package com.example.service.impl;

import com.example.domain.dto.PaperDTO;
import com.example.domain.po.Paper;
import com.example.domain.po.Question;
import com.example.mapper.PaperMapper;
import com.example.service.PaperService;
import com.example.util.PageBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PaperServiceImpl implements PaperService {
    @Autowired
    private PaperMapper paperMapper;

    @Override
    public PageBean<Paper> listByPage(Integer pageNum, Integer pageSize, String name) {
        PageBean<Paper> pg = new PageBean<>();

        PageHelper.startPage(pageNum,pageSize);
        List<Paper> pList=paperMapper.listByPage(name);
        Page<Paper> p = (Page) pList;

        pg.setTotal(p.getTotal());
        pg.setItems(p.getResult());
        return pg;
    }

    @Override
    public void add(PaperDTO paperDTO) {
        //新增试卷
        //会返回主键id插入到paperDTO
        paperMapper.addPaper(paperDTO);
        //将试卷考题新增进中间表
        paperMapper.addPaperAndQuestion(paperDTO.getQuestions(),paperDTO.getId());
    }

    @Override
    public PaperDTO getById(Integer id) {
        Paper paper = paperMapper.getById(id);
        List<Question> qList=paperMapper.PAQGetById(id);
        return new PaperDTO(id,paper.getName(),paper.getType(),null,qList);
    }

    @Override
    public void deleteById(Integer id) {
         paperMapper.deleteById(id);

        paperMapper.deletePAQById(id);
    }

    @Override
    public void edit(PaperDTO paperDTO) {
        paperMapper.editPaper(paperDTO);

        //删除中间表相关数据再重新添加
        paperMapper.deletePAQById(paperDTO.getId());
        paperMapper.addPaperAndQuestion(paperDTO.getQuestions(),paperDTO.getId());
    }
}
